package com.csdj.t309.geamtest.controller;

import com.csdj.t309.geamtest.common.CacheConstant;
import com.csdj.t309.geamtest.common.WebResult;
import com.csdj.t309.geamtest.common.WebResultMsgCode;
import com.csdj.t309.geamtest.entity.User;
import com.csdj.t309.geamtest.service.IUserService;
import com.csdj.t309.geamtest.service.RedisService;
import com.csdj.t309.geamtest.util.UpPhotoNameUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;

@RestController
@RequestMapping("upload")
public class UploadController {
    @Resource
    private RedisService redisService;
    @Resource
    private IUserService iUserService;

    @RequestMapping("image")
    public WebResult singleFileUpload(@RequestParam("file") MultipartFile file,
                                      HttpServletRequest request) {
        try {
            byte[] bytes = file.getBytes();
            String imageFileName = file.getOriginalFilename();
            String fileName = UpPhotoNameUtils.getPhotoName("img",imageFileName);
            Path path = Paths.get("D:\\123456\\" + fileName);
            //“C:\\框架\\D4\\d4_pc_ui\\src\\assets\\images\\img\\”为本地目录
            //写入文件
            Files.write(path, bytes);
            String avatar_url=fileName;
            User user  = new User();
            user.setId(redisService.getObject(CacheConstant.HEADER_UID+request.getHeader("uid")));
            user.setAvatar("http://y416079762.oicp.vip/image/"+avatar_url);
            //把图片名称写入数据库
            //dao层方法
            iUserService.updateTuPian(user);
            System.out.println(fileName+"\n");
            //返回文件名字
            return new WebResult(WebResultMsgCode.SUCCESS).putData("fileName","http://y416079762.oicp.vip/image/"+fileName);
        } catch (IOException e) {
        }
        return new WebResult(WebResultMsgCode.FAIL);
    }


    @RequestMapping("addImage")
    public Integer addImage(String imagePath,
                            HttpServletRequest request){
        User user = new User();
        user.setId(redisService.getObject(CacheConstant.HEADER_UID+request.getHeader(CacheConstant.HEADER_UID)));
        user.setAvatar(imagePath);
        Integer integer = iUserService.updateTuPian(user);
        System.out.println("图片地址："+imagePath);
        return integer;
    }
}
